package com.wkq.util.apk

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/5/13 17:58
 *
 *@Desc:
 */
object ApkInstallUtil {
    /**
     * 安装apk
     */
    fun installApk(context: Context, path: String) {
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val contentUri = FileProvider.getUriForFile(
                    context, context.getApplicationContext().getPackageName() + ".fileProvider",
                    File(path)
                )
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(
                    Uri.fromFile(File(path)), "application/vnd.android.package-archive"
                )
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            ((context) as Activity).startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 是否具有未知来源权限/没有未知来源需要打开未知来源权限
     */
    fun canRequestPackageInstalls(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return context.getPackageManager().canRequestPackageInstalls()
        } else {
            return true
        }
    }
}